<?php

namespace app\admin\controller\car;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 车辆管理-二手车
 *
 * @icon fa fa-circle-o
 */
class Old extends Backend
{

    /**
     * Old模型对象
     * @var \app\admin\model\car\Old
     */
    protected $model = null;

    protected $relationSearch = true;
    protected $searchFields = 'car_brand_name,car_series_name,car_models_name';
    protected $noNeedLogin = ['web_view'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\car\Old;
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->field("car_old.*")
            ->field("u.name,u.nickname,u.mobile")
            ->join('user u','u.id = car_old.user_id',"left")
            ->where($where)
            ->where("verify_status",1)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }



        $car_series_name = input("car_series_name");
        if (!empty($car_series_name)) {
            $params["car_series_name"] = $car_series_name;
        }

        $car_models_name = input("car_models_name");
        if (!empty($car_models_name)) {
            $params["car_models_name"] = $car_models_name;
        }

        $car_brand_name = input("car_brand_name");
        if (!empty($car_brand_name)) {
            $params["car_brand_name"] = $car_brand_name;
        }

        $params["verify_status"] = 1;
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $car_series_name = input("car_series_name");
        if (!empty($car_series_name)) {
            $params["car_series_name"] = $car_series_name;
        }

        $car_models_name = input("car_models_name");
        if (!empty($car_models_name)) {
            $params["car_models_name"] = $car_models_name;
        }

        $car_brand_name = input("car_brand_name");
        if (!empty($car_brand_name)) {
            $params["car_brand_name"] = $car_brand_name;
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 批量热推
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function tui($ids = null)
    {

        $ids = $ids ?: $this->request->post("ids/a");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {

            foreach ($list as $item) {
                if ($item["recommend"] == 0) {
                    $count += Db::name("car_old")->where("id",$item["id"])->update(["recommend"=>1]);
                } else {
                    $count += Db::name("car_old")->where("id",$item["id"])->update(["recommend"=>0]);
                }

            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success("操作成功");
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 批量热搜
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function sou($ids = null)
    {

        $ids = $ids ?: $this->request->post("ids/a");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {

            foreach ($list as $item) {
                if ($item["hot_search"] == 0) {
                    $count += Db::name("car_old")->where("id",$item["id"])->update(["hot_search"=>1]);
                } else {
                    $count += Db::name("car_old")->where("id",$item["id"])->update(["hot_search"=>0]);
                }

            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success("操作成功");
        }
        $this->error(__('No rows were deleted'));
    }


    /**
     * 批量热销
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function xiao($ids = null)
    {

        $ids = $ids ?: $this->request->post("ids/a");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {

            foreach ($list as $item) {
                if ($item["hot_sales"] == 0) {
                    $count += Db::name("car_old")->where("id",$item["id"])->update(["hot_sales"=>1]);
                } else {
                    $count += Db::name("car_old")->where("id",$item["id"])->update(["hot_sales"=>0]);
                }

            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success("操作成功");
        }
        $this->error(__('No rows were deleted'));
    }


    //修改权重
    public function weight()
    {

        $id = input("id");
        $weight = input("weight");
        if (empty($id)){
            $this->error(__('Parameter %s can not be empty', ''));
        }

        Db::name("car_old")->where("id",$id)->update([
            "weight"=>$weight
        ]);

        $this->success("编辑成功");
    }


    //修改权重
    public function masterimgurl()
    {
        $url = input("url");
        echo $this->master_imgUrl_base64($url);
    }


    public function master_imgUrl_base64($url){
        if($url){
            $header = array('User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0','Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3','Accept-Encoding: gzip, deflate',);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            $data = curl_exec($curl);
            $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);
            if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
                $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
                return $imgBase64Code;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
